package org.demo.tomcat;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author  
 * @date    2010-12-13
 * @file    org.demo.tomcat.AutoComplete.java
 */
public class AutoComplete extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String word = req.getParameter("word");
		req.getSession().setAttribute("word", word);
		
		resp.setContentType("text/xml;charset=utf-8");
		PrintWriter out = resp.getWriter();
		out.print(generateXml(word));
		out.flush();
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
	private String generateXml(String word){
		String[] data = getWords(word);
		StringBuffer sb = new StringBuffer();
		sb.append("<words>");
		for (String d : data){
			sb.append("<word>").append(d).append("</word>");
		}
		sb.append("</words>");
		return sb.toString();
	}
	
	private String[] getWords(String word){
		String[] data = {"anyone", "anything", "apple", "appear", 
				"abandon", "breach", "break"};
		List<String> list = new ArrayList<String>();
		for (String d : data){
			if (d.startsWith(word) && !d.equals(word)){
				list.add(d);
			}
		}
		return list.toArray(new String[list.size()]);
	}
}
